//
//  CNProfile.swift
//  SwiftUi
//
//  Created by xm on 03/09/2025.
//

import SwiftUI
import Foundation

struct CNProfile: View {
    @Environment(\.editMode)  var mode

    @State var draftProfile = User.default
    @StateObject var userData: UserData = UserData()

    
    var body: some View {
        
        withUnsafePointer(to: draftProfile) { pointer in
            print("[CNProfile] draftProfile", pointer)
        }
        
        withUnsafePointer(to: userData.userProfile) { pointer in
            print("[CNProfile] userData.userProfile", pointer)
        }
        
        return VStack() {
            HStack {
                if mode?.wrappedValue == .active {
                    Button(action:{
                        self.mode?.animation().wrappedValue = .inactive
//                        self.draftProfile = self.userData.userProfile

                    }){
                        Text("取消")
                        
                    }
                }
                
                Spacer()
                
                EditButton()
            }.padding()
            
            
            
            if mode?.wrappedValue == .inactive {
                CNProfileSummary(profile: userData.userProfile)
                    
            }else{
                CNProfileEditor(profile: $draftProfile)
                .onAppear {
                    print("onAppear userProfile", self.userData.userProfile.prefersSeason)
                    print("onAppear draftProfile", self.draftProfile.prefersSeason)

                    self.draftProfile = self.userData.userProfile
                }
            
                .onDisappear {
                    print("onDisappear userProfile", self.userData.userProfile.prefersSeason)
                    print("onDisappear draftProfile", self.draftProfile.prefersSeason)
                    
                    self.userData.userProfile = self.draftProfile
                }

            }
            
     
               
                
        }.environmentObject(UserData())
    
    }
}

#Preview {
    CNProfile().environmentObject(UserData())
}
